package test;
import itdb1.commun.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.net.InetAddress;

public class UDPSender {
	private DatagramSocket socket;
	
	public UDPSender() throws SocketException {
		socket = new DatagramSocket(4243);
	}
	
	private void sendObject(Object obj) throws IOException {
		ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
		ObjectOutputStream outputObjectStream = new ObjectOutputStream(byteStream);
		outputObjectStream.writeObject(obj);
		outputObjectStream.flush();
		byte[] buffer = byteStream.toByteArray();
		DatagramPacket packet = new DatagramPacket(buffer, buffer.length, InetAddress.getByName("localhost"), 4242);
		socket.send(packet);
	}
	
	public static void main(String[] args) {
		try {
			UDPSender sender = new UDPSender();
			UDPListener listener = new UDPListener(4242);
			
			sender.sendObject(new Bye());
			try {
				Thread.sleep(10);
			}
			catch (InterruptedException e) {
			}
			sender.sendObject(new Message("Tu as une petite bite"));
			
			listener.stop();
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
